import { createWebHistory, createRouter } from 'vue-router'

// static rotute
const routes = [
  {
    path: '/',
    redirect: '/home',
    name: 'Home',
    component: () => import('@/pages/Home.vue'),
    children: [
    ]
  }, 
  {
    path: '/:catchAll(.*)', // /*
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory('/'), // 路由类型
  routes // short for `routes: routes`
})

const loadRoute = (routes) => {
  if (!routes || !Array.isArray(routes)) return
  routes.forEach((route) => {
    // 排除后台系统路由
    if (route.isBackground) return

    const options = {
      path: route.menuPath,
      name: route.pathName,
      component: () => import(`@/views/${route.componentPath}`),
      meta: {
        requiresAuth: (route.requiresAuth === undefined || route.requiresAuth === null) ? true : route.requiresAuth,
        title: route.menuName,
        icon: route.menuIcon
      },
      children: []
    }
    if (route.childList && route.childList.length > 0) {
      options.redirect = route.childList[0].menuPath
      route.childList.forEach((child) => {
        const _options = {
          path: child.menuPath,
          name: child.pathName,
          component: () => import(`@/views/${child.componentPath}`),
          meta: {
            requiresAuth: true,
            title: child.menuName,
            icon: child.menuIcon
          },
          children: []
        }
        if (child.childList && child.childList.length > 0) {
          child.childList.forEach((_child) => {
            _options.redirect = child.childList[0].menuPath
            _options.children.push({
              path: _child.menuPath,
              name: _child.pathName,
              component: () => import(`@/views/${_child.componentPath}`),
              meta: {
                requiresAuth: true,
                title: _child.menuName,
                icon: _child.menuIcon
              }
            })
          })
        }
        options.children.push(_options)
      })
    }
    router.addRoute('Root', options)
  })
}
const clearRoute = (routes) => {
  routes.forEach((item) => {
    if (item.childList && item.childList.length > 0) {
      clearRoute(item.childList)
    } else {
      router.hasRoute(item.pathName) && router.removeRoute(item.pathName)
    }
  })
}
// 加载路由
export const createDynamicRoutes = (dynamicRoutes) => {
  console.log(dynamicRoutes)
  clearRoute(dynamicRoutes)
  if (dynamicRoutes.length) {
    loadRoute(dynamicRoutes)
  }
}

const getInfos = async() => {
  const userInfo_store = userInfoStore()
  const res = await UserMangerApi.getUserInfo('PC') || {}
  userInfo_store.setUserInfo(res)
  const router_store = routerAndPremission()
  await router_store.getRouterAndPremission(res.roleId)

  const team_store = teamStore()
  team_store.setTeamId(res.teamId)
  team_store.setTeamName(res.teamName)
}
// 全局前置守卫
let firstFlag = false
router.beforeEach((to, from, next) => {
  // 进入邀请页面
  if (to.path === '/invite') {
    const token = TokenStorage.get()
    if (token) {
      next()
    } else {
      next({ path: '/login', query: to.query })
    }
    firstFlag = false
    return
  }
  // 登录后才能相关功能页
  const router_store = routerAndPremission()
  const userInfo_store = userInfoStore()
  if (to.path.includes('/login')) { // 登录页面
    router_store.resetRouterAndPermission(true) // 重置路由 不包含许可中心
    sessionStorage.clear()
    userInfo_store.setUserInfo({}) // 只有登陆页面重置用户信息  许可页面头部需要用户信息
    firstFlag = false
    next()
  } else if (to.path.includes('/license')) { // 许可页面
    router_store.resetRouterAndPermission(false) // 重置路由 包含许可中心
    sessionStorage.clear()
    firstFlag = false
    next()
  } else {
    const token = TokenStorage.get()
    if (!token) {
      next({ path: '/login' })
    } else {
      if (!firstFlag) {
        getInfos().then(() => {
          const router_store = routerAndPremission()
          const currentRoute = window.location.pathname
          if (currentRoute !== '/') {
            if (currentRoute === '/login' || currentRoute === '/invite' || currentRoute === '/license') {
              next({ path: router_store.router[0].menuPath })
            } else {
              const search = window.location.search
              const query = {}
              if (search) {
                const splitsFirst = search.split('?')
                const splitsSecond = splitsFirst[1].split('&')
                splitsSecond.forEach(item => {
                  const splitFinal = item.split('=')
                  query[splitFinal[0]] = splitFinal[1]
                })
              }
              next({ path: currentRoute, query })
            }
          } else {
            next({ path: router_store.router[0].menuPath })
          }

          firstFlag = true
        })
      } else {
        next()
      }
    }
  }
})
export default router
